package org.ghost.wechat.platform.common.db;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.ghost.wechat.platform.common.enumeration.DbTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Administrator
 */
@Aspect
@Component
public class DbTypeInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(DbTypeInterceptor.class);

    private final String pointcut = "execution(* org.ghost.wechat.platform.service..*.*(..)) || execution(* com.baomidou.mybatisplus.service..*.*(..))";

    @Pointcut(value = pointcut)
    public void dbType() {
    }

    @Before("dbType()")
    void before(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        DbTypeSwitch dbTypeSwitch = method.getAnnotation(DbTypeSwitch.class);
        DbTypeEnum dbType = dbTypeSwitch != null ? dbTypeSwitch.dbType() : DbTypeEnum.MASTER;

        logger.info("*****DbTypeInterceptor切换数据源为:{}", dbType);

        DynamicDataSourceHolder.setDbType(dbType);
    }

    @After("dbType()")
    void after() {
        logger.info("*****DbTypeInterceptor移除数据源");
        DynamicDataSourceHolder.clearDbType();
    }
}
